module.exports = app => {
  const router = require('express').Router()
  const httpAuth = require('../../middleware/httpAuth')
  // 获取用户信息
  router.get('/admin/api/user/info', httpAuth(), async (req, res, next) => {
    try {
      res.response(200, '查询成功', req.user)
    } catch (error) {
      next(error)
    }
  })

  const group = require('../../models/group')
  const { uniqueArr } = require('../../utils/index')
  const menu = require('../../models/menu')


  /**
   * 获取对应管理员权限的菜单列表
   */
  router.get('/admin/api/admin/sidebarMenuList', httpAuth(), async (req, res, next) => {
    try {
      const model = await group.findOne({ where: { id: req.user.groupId } })
      let menuList = []
      let ids = model.permission.split(',')
      let pids = []
      for (let i = 0; i < ids.length; i++) {
        const menuRes = await menu.findOne({ where: { id: ids[i], hidden: 0, menuType: { $lt: 3 } } })
        if (menuRes) {
          menuList.push(menuRes)
          if (menuRes.pid) {
            if (!pids.includes(menuRes.pid)) {
              pids.push(menuRes.pid)
            }
          }
        }
      }
      for (let i = 0; i < pids.length; i++) {
        const parentMenu = await menu.findOne({ where: { id: pids[i], hidden: 0, menuType: { $lt: 3 } } })
        if (parentMenu) menuList.push(parentMenu)
      }
      res.response(200, '获取成功', uniqueArr(menuList))
    } catch (error) {
      next(error)
    }
  })


  /**
  * 获取对应管理员权限的页面按钮(权限标识)
  */
  router.get('/admin/api/admin/perms', httpAuth(), async (req, res, next) => {
    try {
      const model = await group.findOne({ where: { id: req.user.groupId } })
      let perms = []
      let ids = model.permission.split(',')
      for (let i = 0; i < ids.length; i++) {
        const perm = await menu.findOne({ where: { id: ids[i], hidden: 0, menuType: 3 } })
        if (perm) perms.push(perm.permission)
      }
      res.response(200, '获取成功', perms)
    } catch (error) {
      next(error)
    }
  })

  app.use(router)
}